#pragma once

#include<bits/stdc++.h>
#include<sys/types.h>
#include<unistd.h>
#include<sys/wait.h>
#include<stdlib.h>
#include<sys/stat.h>
#include<string.h>
#include<fcntl.h>
#include<string> 
#include<stdio.h>
#include<time.h>
#define Info 0
#define Debug 1
#define Warning 2
#define Error 3
#define Fatal 4

#define SIZE 1024
#define PATH "./log/"
#define SCREEN 1
#define ONEFILE 2
#define CLASSFILE 3 //分类文件,形成.Debug,.Fatal这种

#define LOGFILE "log.txt"
using namespace std;
class Log{
public:
    Log()
    {
        printMethod = SCREEN;
    }
    void Enable(int method)
    {
        printMethod = method;
    }

string LevelToString(int level)
{
    switch(level)
    {
        case Info:return "Info";
        case Debug:return "Debug";
        case Warning:return "Warning";
        case Fatal:return "Fatal";
        default:return "None";
    }
    return nullptr;
}
void PrintLog(int level,const string& logtxt)
{
    switch (printMethod) 
    {
       case SCREEN:
             cout << logtxt;
       break;
       case ONEFILE:
            PrintOneFile(logtxt);
       break;
       case CLASSFILE:
            PrintClassFile(level,logtxt);
       break;
       default:
       break;
    }
    
}
void PrintOneFile(const string& logtxt)
{
    int fd = open(LOGFILE,O_WRONLY|O_CREAT|O_APPEND,0666);
    if(fd < 0) return ;
    write(fd,logtxt.c_str(),logtxt.size());
    close(fd);
}
void PrintClassFile(int level,const string& logtxt)
{
    string f = PATH;
    string filename = f + LOGFILE;
    filename += '.';
    filename += LevelToString(level);
    int fd = open(filename.c_str(),O_WRONLY|O_CREAT|O_APPEND,0666);
    if(fd < 0) return ;
    write(fd,logtxt.c_str(),logtxt.size());
    close(fd);
}
 void operator()(int level,const char* format, ...)
 {
     //这个可以直接取代logmessage
     char buff[SIZE];
    // cout << time(nullptr) << endl;
   time_t t = time(nullptr);
   struct tm* ctime = localtime(&t);
   snprintf(buff,sizeof(buff),"[%s][%d-%d-%d:%d:%d:%d]",LevelToString(level).c_str(),ctime->tm_year+1900,ctime->tm_mon+1,ctime->tm_mday,ctime->tm_hour,ctime->tm_min,ctime->tm_sec);
   
    char logtxt[SIZE];
    va_list s;
    va_start(s,format);
    vsnprintf(logtxt,sizeof(logtxt),format,s);
    va_end(s);
   char fin[SIZE * 2];
   snprintf(fin,sizeof(fin),"%s %s\n",buff,logtxt);
   PrintLog(level,fin);
 }
  private:
  int printMethod;

};


Log l;